﻿using Common.Library;
using Microsoft.Phone.Scheduler;
using OnlineVideos.Data;
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Threading;

namespace OnlineVideos.ViewModels
{
   public class AddReminder
    {
       public DispatcherTimer timer = new DispatcherTimer();
       IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
       public void Add()
       {
            int CheckShowID = 1;
            int CheckID = 1;
            int CheckValue = 0;
            OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            if (context.NotifyTable.FirstOrDefault() != null)
            {
                if (settings.Contains("LastCheckedShowID"))
                {
                    CheckID = (int)settings["LastCheckedShowID"];
                    if (CheckID == context.NotifyTable.Max(i => i.ID))
                    {
                        CheckID = 1;
                    }
                }

                CheckShowID = context.NotifyTable.Where(i => i.ID == CheckID).FirstOrDefault().ShowID;
                CheckValue = context.NotifyTable.Where(i => i.ID == CheckID).FirstOrDefault().LessThan;
                int[] Values = new int[2];
                Values[0] = CheckID;
                Values[1] = CheckValue;
                var Shows = context.Infotable.Where(i => i.ShowID == CheckShowID).FirstOrDefault();
                WebClient wb = new WebClient();
                wb.DownloadStringAsync(new Uri(Shows.NavigationUri, UriKind.Absolute), Values);
                wb.DownloadStringCompleted += wb_DownloadStringCompleted;
            }
            else
            {
                timer.Stop();
            }
          
       }
       public int getNumberOfOccurencies(String inputString, String checkString)
       {
           if (checkString.Length > inputString.Length || checkString.Equals("")) { return 0; }
           int lengthDifference = inputString.Length - checkString.Length;
           int occurencies = 0;
           for (int i = 0; i < lengthDifference; i++)
           {
               if (inputString.Substring(i, checkString.Length).Equals(checkString)) { occurencies++; i += checkString.Length - 1; }
           }
           return occurencies;
       }
       void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
       {
           int[] values=new int[2];
           values=(int[])e.UserState;
           int BeforeTextPosition = default(int);
            int BeforeTextLength = default(int);
            string CurrentSelectedText = string.Empty;
            int NoOfOccurrences = default(int);

            OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            string SelectedText = context.Infotable.Where(i => i.ShowID == Convert.ToInt32(e.UserState.ToString())).Select(i => i.SelectedText).FirstOrDefault().Replace("\n", "").Replace("\r", "").Replace("<br>", "<br />").Replace("\t", "");
            string BeforeText = context.Infotable.Where(i => i.ShowID == Convert.ToInt32(e.UserState.ToString())).Select(i => i.BeforeText).FirstOrDefault().Replace("\n", "").Replace("\r", "").Replace("<br>", "<br />").Replace("\t", "");
            string AfterText = context.Infotable.Where(i => i.ShowID == Convert.ToInt32(e.UserState.ToString())).Select(i => i.AfterText).FirstOrDefault().Replace("\n", "").Replace("\r", "").Replace("<br>", "<br />").Replace("\t", "");

            if (e.Result != null)
            {

                string PageHtml = e.Result.ToString().Replace("\n", "").Replace("\r", "").Replace("<br>", "<br />").Replace("\t", "");
                NoOfOccurrences = getNumberOfOccurencies(PageHtml, BeforeText);
                if (NoOfOccurrences == 1)
                {
                    BeforeTextPosition = PageHtml.IndexOf(BeforeText);
                    BeforeTextLength = BeforeText.Length;
                    int BeforeTextEndPosition = BeforeTextPosition + BeforeTextLength;
                    string RemainingText = PageHtml.Substring(BeforeTextEndPosition);
                    int AfterTextposition = RemainingText.IndexOf(AfterText);
                    CurrentSelectedText = RemainingText.Substring(0, AfterTextposition);
                    if (Convert.ToInt32(CurrentSelectedText) < values[1])
                    {
                        AddRemOrAlaram(values[0]);
                    }
                }
                else
                {
                    CurrentSelectedText = "Error";
                }
                if (settings.Contains("LastCheckedReminderShowID"))
                    settings["LastCheckedReminderShowID"] = values[0];
                else
                    settings.Add("LastCheckedReminderShowID", values[0]);
            }
       }
       public void AddRemOrAlaram(int Id)
       {
           OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
           ReminderTable Rt = context.NotifyTable.Where(i => i.ID == Id).FirstOrDefault();
           if (Rt.Type == "Reminder")
           {
               string name = System.Guid.NewGuid().ToString();
               Reminder reminder = new Reminder(name);
               reminder.Title = Rt.Title;
               reminder.Content = Rt.Description;
               reminder.BeginTime = System.DateTime.Now.AddMinutes(1);
               reminder.ExpirationTime = System.DateTime.Now.AddMinutes(2);
               if (ScheduledActionService.Find(name) != null)
               {
                   ScheduledActionService.Remove(name);
                   ScheduledActionService.Add(reminder);
               }
               else
               {
                   ScheduledActionService.Add(reminder);
               }
           }
           else
           {
               string name = System.Guid.NewGuid().ToString();
               Alarm alarm = new Alarm(name);
               alarm.Content = Rt.Description;
               alarm.Sound = new Uri("/RingTones/smokealarm.wav", UriKind.Relative);
               alarm.BeginTime = System.DateTime.Now.AddMinutes(1);
               alarm.ExpirationTime = System.DateTime.Now.AddMinutes(2);
               if (ScheduledActionService.Find(name) != null)
               {
                   ScheduledActionService.Remove(name);
                   ScheduledActionService.Add(alarm);
               }
               else
               {
                   ScheduledActionService.Add(alarm);
               }
           }
       }
    }
}
